/**
 * media should be update every day
 * article shouldbe update everyday
 * 
 * image file should be update every 10 tens
 * 
 * */

package com.taptech.doufu.util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;

import com.taptech.doufu.sdk.universalimageloader.core.assist.FlushedInputStream;
import com.taptech.doufu.sdk.universalimageloader.core.assist.ImageSize;
import com.taptech.doufu.sdk.universalimageloader.core.assist.ViewScaleType;
import com.taptech.doufu.sdk.universalimageloader.utils.ImageSizeUtils;
import com.taptech.doufu.listener.CommmonImp;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.constant.Constant.AppDir;
import com.taptech.doufu.constant.Constant.ImageType;
import com.taptech.doufu.constant.Constant.WeMediaCache;
import com.taptech.doufu.bean.MyAccountOperation;
import com.taptech.doufu.net.retrofit.api.ApiClient;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;

public class CacheUtil {

	private static long mCurrentTime;
	private static long mMaxDiffDays = 60 * 24 * 3600 * 1000; // 2 month

	private final static String[] mKeepFiles = {
			WeMediaCache.CACHE_FILE_ALL_WE_MEDIA_TITLE,
			WeMediaCache.CACHE_FILE_CHOOSE_ARTICLE,
			WeMediaCache.CACHE_FILE_CHOOSE_WE_MEDIA };


	public static String getMarketCachePathBySexType(String sexType) {
		String path;
		if (ApiClient.SEX_TYPE_BL.equals(sexType)) {
			path = CommmonImp.Home_novel_market;
		}else if (ApiClient.SEX_TYPE_UN_BL.equals(sexType)){
			path = CommmonImp.Home_novel_un_market;
		}else{
			path = CommmonImp.Home_novel_gay_market;
		}
		return path;
	}

    public static String getBannerCachePathBySexType(String sexType) {
        String path;
        if (ApiClient.SEX_TYPE_BL.equals(sexType)) {
            path = CommmonImp.Home_novel_banner;
        }else if (ApiClient.SEX_TYPE_UN_BL.equals(sexType)){
            path = CommmonImp.Home_novel_UN_banner;
        }else{
            path = CommmonImp.Home_novel_gay_banner;
        }
        return path;
    }

    public static String getCategoryCachePathBySexType(String sexType) {
        String path;
        if (ApiClient.SEX_TYPE_BL.equals(sexType)) {
            path = CommmonImp.Home_novel_category;
        }else if (ApiClient.SEX_TYPE_UN_BL.equals(sexType)){
            path = CommmonImp.Home_novel_UN_category;
        }else{
            path = CommmonImp.Home_novel_gay_category;
        }
        return path;
    }

    public static String getTopicCachePathBySexType(String sexType) {
        String path;
        if (ApiClient.SEX_TYPE_BL.equals(sexType)) {
            path = CommmonImp.Home_novel_list1;
        }else if (ApiClient.SEX_TYPE_UN_BL.equals(sexType)){
            path = CommmonImp.Home_novel_un_list1;
        }else{
            path = CommmonImp.Home_novel_gay_list1;
        }
        return path;
    }

	public static void saveDraftData(String draft,File saveFile){

		if (saveFile == null) {
			return;
		}

		if (saveFile != null && saveFile.getParentFile() != null) {
			saveFile.getParentFile().mkdirs();
		}

		Writer out = null;
		try {
			out = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(saveFile), "UTF-8"));
			out.write(draft);
			out.close();
			out = null;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			out = null;
		}
	}
	
	public static String readDraft(File saveFile) {
		String draft = null;

		if (saveFile == null||!saveFile.exists()) {
			return draft;
		}

		try {
			InputStream fIS = new FileInputStream(saveFile);
			BufferedInputStream bin = new BufferedInputStream(fIS);
			byte bts[] = new byte[bin.available()];
			bin.read(bts);
			bin.close();
			fIS.close();
			draft = new String(bts, "UTF-8");

		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} 
		return draft;

	}

	public static void saveJsonDataToCache(String jsonData, File cacheFile) {

		if (cacheFile == null) {
			return;
		}

		if (cacheFile != null && cacheFile.getParentFile() != null) {
			cacheFile.getParentFile().mkdirs();
		}

		Writer out = null;
		try {
			out = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(cacheFile), "UTF-8"));
			out.write(jsonData);
			out.close();
			out = null;
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			out = null;
		}

	}





	public static JSONObject readJsonDataFromCache(File cacheFile) {

		JSONObject jsonObject = null;

		if (cacheFile == null||!cacheFile.exists()) {
			return jsonObject;
		}

		try {
			InputStream fIS = new FileInputStream(cacheFile);
			BufferedInputStream bin = new BufferedInputStream(fIS);
			byte bts[] = new byte[bin.available()];
			bin.read(bts);
			bin.close();
			fIS.close();
			String targetStr = new String(bts, "UTF-8");
			jsonObject = new JSONObject(targetStr);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} catch (JSONException e) {
			e.printStackTrace();
			return null;
		}
		return jsonObject;

	}


	public static void saveBitmapToCache(Bitmap bitmap, String type,
			File bitmapFile) {

		if (bitmapFile != null && bitmapFile.getParentFile() != null) {
			bitmapFile.getParentFile().mkdirs();
		}

		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		// bitmap.

		if (ImageType.IMAGE_PNG.equalsIgnoreCase(type)) {
			bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
		} else {
			bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		}

		// InputStream is = new ByteArrayInputStream(baos.toByteArray());
		byte[] data = baos.toByteArray();

		try {
			FileOutputStream fos = new FileOutputStream(bitmapFile);
			fos.write(data);
			fos.close();

			fos = null;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}



	/**
	 * 从缓存中读取图片 every time , we use the file , we will set the file's last
	 * modified time use for clear cache
	 */
	public static Bitmap readBitmapFromCache(String type, File bitmapFile) {
		Bitmap bitmap = null;
		if (bitmapFile == null) {
			return null;
		}
		try {

			bitmap = BitmapFactory.decodeStream(new BufferedInputStream(
					new FileInputStream(bitmapFile), 16 * 1024));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			bitmap = null;
			e.printStackTrace();
		} catch (OutOfMemoryError e) {
			bitmap = null;
			e.printStackTrace();
		}
		return bitmap;

	}


	/**
	 * 从缓存中读取图片 every time , we use the file , we will set the file's last
	 * modified time use for clear cache
	 */
	public static Bitmap readBitmapFromCache(File bitmapFile) {
		Bitmap bitmap = null;
		if (bitmapFile == null) {
			return null;
		}
		try {
			Options options = new Options();
			options.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(bitmapFile.getAbsolutePath(), options);
			int scale = 1;
			if(options.outWidth> ScreenUtil2.SCREEN_PX_WIDTH)
			{
				ImageSize srcSize = new ImageSize(options.outWidth, options.outHeight);
				ImageSize targetSize = new ImageSize(ScreenUtil2.SCREEN_PX_WIDTH/2, ScreenUtil2.SCREEN_PX_HEIGHT/2);
				scale = ImageSizeUtils.computeImageSampleSize(srcSize, targetSize, ViewScaleType.FIT_INSIDE, true);
			}
			options.inJustDecodeBounds = false;
			options.inSampleSize =scale;
			BufferedInputStream is = new BufferedInputStream(
					new FileInputStream(bitmapFile));
			bitmap = BitmapFactory.decodeStream(new FlushedInputStream(is),
					null, options);
		} catch (FileNotFoundException e) {
			bitmap = null;
			e.printStackTrace();
		} catch (OutOfMemoryError e) {
			bitmap = null;
			e.printStackTrace();
		}
		return bitmap;

	}

	public static void clearCacheByUser() {
		clearCache(AppDir.DIR_CACHE_MAIN);
		clearCache(AppDir.DIR_CACHE_ARTICLE);
		clearCachePapers();
		clearCacheImage();
		clearCacheMedia();
		clearCacheTmp();

	}

	public static void clearCache() {
		clearCache(AppDir.DIR_CACHE_MAIN);
		clearCache(AppDir.DIR_CACHE_ARTICLE);
		clearCachePapers();
	}

	private static void clearCache(String cache) {

		File dirFile = new File(cache);

		if (dirFile == null || !dirFile.exists() || !dirFile.isDirectory()) {
			return;
		}

		File[] files = dirFile.listFiles();

		if (files == null) {
			return;
		}

		for (File file : files) {
			if (file == null) {
				continue;
			}

			// only keep the WeMediaCache.CACHE_FILE_CHOOSE_ARTICLE
			if (file.isFile()) {
				if (file.getName() != null) {
					TTLog.e("clearCacheMain", file.getPath());
					file.delete();
				}
			}
		}
	}

	// clear the /mnt/sdcard/WeMedia/cache/article
	private static void clearCachePapers() {

		File dirFile = new File(AppDir.DIR_CACHE_PAPER);

		if (dirFile == null || !dirFile.exists() || !dirFile.isDirectory()) {
			return;
		}

		File[] files = dirFile.listFiles();

		if (files == null) {
			return;
		}

		for (File file : files) {
			if (file == null) {
				continue;
			}

			// only keep the WeMediaCache.CACHE_FILE_CHOOSE_ARTICLE
			if (file.isFile()) {
				if (file.getName() != null) {
					TTLog.e("clearCachePapers", file.getPath());
					file.delete();
				}
			}
		}
	}

	// clear the /mnt/sdcard/WeMedia/cache/image
	// only clear *.png & *.jpg, not the *.img_cache
	private static void clearCacheImage() {
		File dirFile = new File(Constant.AppDir.DIR_CACHE_IMAGE);

		if (dirFile == null || !dirFile.exists() || !dirFile.isDirectory()) {
			return;
		}

		File[] files = dirFile.listFiles();

		if (files == null) {
			return;
		}

		for (File file : files) {
			if (file == null) {
				continue;
			}

			// only keep the *.img_cache && avtar png or jpg

			if (isImageFileCanbeClear(file)) {
				if (MyAccountOperation.getAvatar() == null
						|| !StringUtil.convertUrlToFileName(
								MyAccountOperation.getAvatar()).equals(
								file.getName())) {
					TTLog.e("clearCacheImage", file.getPath());
					file.delete();
				}
			}

		}
	}

	private static void clearCacheMedia() {
		// do nothing here
	}

	private static void clearCacheTmp() {
		File tmpFile = new File(AppDir.DIR_TMP);

		File[] files = tmpFile.listFiles();

		if (files == null) {
			return;
		}

		for (File file : files) {
			if (file != null) {
				TTLog.e("clearCacheTmp", file.getPath());
				file.delete();
			}
		}

	}

	private static boolean isImageFileCanbeClear(File file) {
		if (file == null) {
			return false;
		}

		String name = file.getName();

		if (name == null) {
			return false;
		}

		int lastDotIndex = name.lastIndexOf("\\.");

		if (lastDotIndex < 0 || lastDotIndex + 1 >= name.length()) {
			return false;
		}

		String type = name.substring(lastDotIndex + 1);

		if (type == null) {
			return false;
		}

		if (type.equalsIgnoreCase(ImageType.IMAGE_PNG)
				|| type.equalsIgnoreCase(ImageType.IMAGE_JPEG_1)
				|| type.equalsIgnoreCase(ImageType.IMAGE_JPEG_2)
				|| type.equalsIgnoreCase(ImageType.IMAGE_JPEG_3)
				|| type.equalsIgnoreCase(ImageType.IMAGE_JPEG_4)
				|| type.equalsIgnoreCase(ImageType.IMAGE_BMP_1)
				|| type.equalsIgnoreCase(ImageType.IMAGE_BMP_2)) {
			return true;
		}

		return false;

	}

}
